package com.zx.idc.backend.gui.api.management.scheduler.service;

import com.zx.idc.common.attributes.SchedulerAttributes;
import com.zx.idc.common.exception.EncryptException;
import com.zx.idc.common.spring.SpringConfigUtil;
import com.zx.idc.ds.ins.entity.InsMonitor;
import com.zx.idc.ds.ins.service.IInsMonitorService;
import com.zx.idc.internal.exception.SendMessageException;
import com.zx.idc.qc.constants.ScheduleJobConstants;
import com.zx.idc.qc.core.QuartzTaskService;
import com.zx.idc.qc.entity.TaskEntity;
import com.zx.idc.qc.exception.JobExistsException;
import com.zx.idc.qc.exception.QuartzJobException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ReportMonitorLogJobServer {

    @Autowired
    private QuartzTaskService quartzTaskService;

    @Autowired
    private IInsMonitorService iInsMonitorService;

    /**
     * 生成任务调度
     * 上报过滤日志
     *
     * @param commandId
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void generateScheduler(String commandId) throws ParseException, JobExistsException, QuartzJobException, SendMessageException, EncryptException {
        InsMonitor insMonitor = iInsMonitorService.selectById(commandId);
        HashMap<String, Object> jobDataMap = new HashMap<>();
        TaskEntity taskEntity = getTaskEntity(insMonitor, jobDataMap);
        quartzTaskService.addCronTask(taskEntity);
    }

    private TaskEntity getTaskEntity(InsMonitor insMonitor, Map<String, Object> jobDataMap) {
        return new TaskEntity()
            .setJobClass("com.zx.idc.api.management.scheduler.job.ReportMonitorLogDataJob")
            .setStartTime(new Date().getTime())
            .setJobGroup(ScheduleJobConstants.SCHEDULE_INSTRUCTION_GROUP)
            .setJobName(String.format("reportMonitorLogDataJob_%s", insMonitor.getId()))
            .setJobDescription("上报监测日志任务")
            .setCronExpression(SpringConfigUtil.get(SchedulerAttributes.MONITOR_REPORT_CRON))
            .setJobDataMap(jobDataMap);
    }
}
